package com.example.test2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    DBOpenHelper dbOpenHelper;
    SQLiteDatabase db;
    private TextView text;
    private EditText editAccount;
    private EditText editPassword;

    private Button btnLogin;
    private Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbOpenHelper=new DBOpenHelper(this,"users.db",null,2);
        db=dbOpenHelper.getWritableDatabase();
        initView();
    }
    /*
    初始化控件
     */

    private void initView() {
        text = (TextView) findViewById(R.id.text);
        editAccount = (EditText) findViewById(R.id.edit_account);
        editPassword = (EditText) findViewById(R.id.edit_password);

        btnLogin = (Button) findViewById(R.id.btn_login);
        btnRegister = (Button) findViewById(R.id.btn_register);
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                check();

                break;
            case R.id.btn_register:
                startActivity(new Intent(this,RegisterActivity.class));
                finish();
                break;
        }
    }
    boolean a=false;
    /*
    判断用户名，密码是否输入正确
     */
    public void check(){

        Cursor cursor=db.query("user",null,null,null,null,null,null);
        while (cursor.moveToNext()) {
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            if (username.equals(editAccount.getText().toString())&&password.equals(editPassword.getText().toString())){
                a=true;
                break;
            }
            else {
                a=false;
            }
        }
        cursor.close();
        if (a){
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this,DetailsActivity.class));
            finish();
        }else {

            Toast.makeText(this, "登录失败,账号或密码不正确", Toast.LENGTH_SHORT).show();
        }
    }



}